package com.pulaien.shop.controller;


import com.pulaien.common.core.controller.BaseController;
import com.pulaien.common.core.domain.AjaxResult;
import com.pulaien.common.core.domain.entity.SysUser;
import com.pulaien.common.core.page.TableDataInfo;
import com.pulaien.common.utils.ConstantsUtil;
import com.pulaien.common.utils.SecurityUtils;
import com.pulaien.system.domain.ConfigAddressInfo;
import com.pulaien.system.domain.ConfigLogisticsCompany;
import com.pulaien.system.domain.Container;
import com.pulaien.system.domain.dto.*;
import com.pulaien.system.mapper.ConfigAddressInfoMapper;
import com.pulaien.system.mapper.SysAreaMapper;
import com.pulaien.system.service.IConfigLogisticsCompanyService;
import com.pulaien.system.service.IContainerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;


/**
 * 商城批次Controller
 *
 * @author pulaien
 * @date 2023-04-06
 */
@RestController
@RequestMapping("/shop/container")
@Api(tags = "商城端批次管理")
public class ShopContainerController extends BaseController {


    @Resource
    private IContainerService containerService;
    @Resource
    private ConfigAddressInfoMapper configAddressInfoMapper;
    @Resource
    private IConfigLogisticsCompanyService configLogisticsCompanyService;
    @Resource
    private SysAreaMapper sysAreaMapper;

    @ApiOperation(value = "装箱批次分页获取（检索）")
    @RequestMapping(value = "/getAllContainerList", method = RequestMethod.GET)
    @ResponseBody
    public TableDataInfo getAllContainerList(ContainerSearchConditionsDto containerSearchConditions) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        containerSearchConditions.setCustomerId(currentUser.getUserId());
        startPage();
        return containerService.getPageContainerList(containerSearchConditions);
    }



    @ApiOperation(value = "装箱批次分页获取（检索）")
    @RequestMapping(value = "/h5/getAllContainerList", method = RequestMethod.GET)
    @ResponseBody
    public TableDataInfo getH5AllContainerList(ContainerSearchConditionsDto containerSearchConditions) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        containerSearchConditions.setCustomerId(currentUser.getUserId());
        startPage();
        TableDataInfo pageContainerList = containerService.getPageContainerList(containerSearchConditions);

        List<ExtContainer> rows = (List<ExtContainer>) pageContainerList.getRows();
        List<ExtContainer> rowsNew = new ArrayList<>();

        for(ExtContainer s : rows)
             {

                    ContainerSearchConditionsDto con = new ContainerSearchConditionsDto();
                         con.setContainerBatchNo(s.getContainerBatchNo());
                    AjaxResult containerOrderList = getContainerOrderList(con);
                    List<ExtContainerOrderDto> data = (List<ExtContainerOrderDto>)containerOrderList.get("data");
                    List<String> orderPicList = new ArrayList<>();
                    AtomicReference<Integer> alreadyOrderProductSize = new AtomicReference<>(0);
                    AtomicReference<Integer> orderProductSize = new AtomicReference<>(0);

                    data.forEach(
                            c -> {
                                if(StringUtils.isNotBlank(c.getPictureUrl())) {
                                    orderPicList.add(c.getPictureUrl());
                                }
                                //已装箱数量 alreadyGoodsCount
                                //装箱数量 containerGoodsCount
                                if(c.getAlreadyGoodsCount() != 0) {
                                    alreadyOrderProductSize.set(alreadyOrderProductSize.get() + c.getAlreadyGoodsCount());
                                }

                                if(c.getContainerGoodsCount() != 0) {
                                    orderProductSize.set(orderProductSize.get() + c.getContainerGoodsCount());
                                }

                            }
                    );

                    s.setOrderPicList(orderPicList);
                    s.setOrderProductSize(orderProductSize.get() != null ? orderProductSize.get() : 0 );
                    s.setAlreadyOrderProductSize(alreadyOrderProductSize.get() != null ? alreadyOrderProductSize.get() : 0 );
                    rowsNew.add(s);

                };
        pageContainerList.setRows(rowsNew);
        return pageContainerList;
    }




    @ApiOperation("查询统计数量")
    @RequestMapping(value = "/getStatisticalNum", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getStatisticalNum(ContainerSearchConditionsDto containerSearchConditions) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        containerSearchConditions.setCustomerId(currentUser.getUserId());

        return AjaxResult.success(containerService.getStatisticalNum(containerSearchConditions));
    }

    @ApiOperation(value = "修改装箱单")
    @RequestMapping(value = "/modifyContainerOrder", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult modifyContainerOrder(@RequestBody Container containerOrderDto) {
        //获取当前用户
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        return containerService.modifyContainerOrder(containerOrderDto, currentUser.getUserId());
    }

    @ApiOperation(value = "获取本批次下的所有装箱单")
    @RequestMapping(value = "/getContainerOrderList", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult getContainerOrderList(@RequestBody ContainerSearchConditionsDto con) {
        return containerService.getContainerOrderList(con);
    }

    @ApiOperation(value = "导出批次账单")
    @RequestMapping(value = "/exportObtainFBAOrder", method = RequestMethod.POST)
    public AjaxResult exportObtainFBAOrder(HttpServletResponse response, @RequestBody ContainerOrderDto containerOrderDto) throws Exception {

        return containerService.exportObtainFBAOrder(containerOrderDto.getContainerBatchNo());
    }

    @ApiOperation(value = "获取支付订单")
    @RequestMapping(value = "/getObtainFBAOrder", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult getObtainFBAOrder(@RequestBody ContainerOrderDto containerOrderDto, HttpServletRequest request) {
        String headerLanguage = request.getHeader("Accept-Language");
        //获取当前用户
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        return containerService.getObtainFBAOrder(containerOrderDto.getContainerBatchNo(), currentUser, headerLanguage, containerOrderDto.getToCFlag());
    }


    @ApiOperation("支付")
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult pay(@RequestBody ContainerPayParam containerPayParam) {
        return containerService.pay(containerPayParam);
    }

    /**
     * PayPal 支付成功 回调
     *
     * @param paymentId
     * @param payerId
     */
    @GetMapping("/payPalSuccess")
    public AjaxResult payPalSuccess(@RequestParam("paymentNumber") String paymentNumber, @RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId) {
        return containerService.payPalSuccess(paymentNumber, paymentId, payerId);
    }

    /**
     * paypal 回调 取消支付
     *
     * @throws IOException
     */
    @GetMapping("/payPalCancel")
    public AjaxResult payPalCancel(@RequestParam("paymentNumber") String paymentNumber) {
        return containerService.payPalCancel(paymentNumber);
    }

    @ApiOperation(value = "获取收货地址")
    @RequestMapping(value = "/obtainReceivingAddress", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult obtainReceivingAddress() {
        List<ExtConfigAddressInfoDto> list = containerService.obtainReceivingAddress();
        return AjaxResult.success(list);
    }

    @ApiOperation(value = "发货地址")
    @RequestMapping(value = "/sendReceivingAddress", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult sendReceivingAddress() {
        List<ExtConfigAddressInfoDto> RAList = containerService.sendReceivingAddress();
        return AjaxResult.success(RAList);
    }

    @ApiOperation(value = "新增装箱单")
    @RequestMapping(value = "/addContainerOrder", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addContainerOrder(HttpServletRequest request, @RequestBody ContainerOrderDto containerOrderDto) {


        ConfigLogisticsCompany configLogisticsCompany = configLogisticsCompanyService.selectConfigLogisticsCompanyById(containerOrderDto.getLogisticsCompanyId());
        containerOrderDto.setLogisticeCompany(configLogisticsCompany.getCompanyName());



        String lang = request.getHeader("Accept-Language");
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        Long id = containerOrderDto.getId();
        ConfigAddressInfo addressInfo = configAddressInfoMapper.selectById(id);
        StringBuilder sendArea = new StringBuilder();
        StringBuilder address = new StringBuilder();
        if (StringUtils.isNotEmpty(addressInfo.getProvinceName())) {
            address.append(addressInfo.getProvinceName()).append(" ");
            sendArea.append(addressInfo.getProvinceName()).append(" ");
        }
        if (StringUtils.isNotEmpty(addressInfo.getCityName())) {
            address.append(addressInfo.getCityName()).append(" ");
            sendArea.append(addressInfo.getCityName()).append(" ");
        }
        if (StringUtils.isNotEmpty(addressInfo.getAreaName())) {
            address.append(addressInfo.getAreaName()).append(" ");
            sendArea.append(addressInfo.getAreaName()).append(" ");
        }

        String addressStr = address.append(addressInfo.getAddressInfo()).toString();
        containerOrderDto.setRecipientAddress(addressStr);
        containerOrderDto.setDeliveryPhone(addressInfo.getReceiverPhone());
        containerOrderDto.setRecipientName(addressInfo.getReceiverName());
        containerOrderDto.setSendArea(sendArea.toString());
        containerOrderDto.setUserId(currentUser.getUserId());
        containerOrderDto.setUserName(currentUser.getUserName());
        containerOrderDto.setEmailAddress(currentUser.getEmail());
        return containerService.addContainerOrder(containerOrderDto);
    }

    @ApiOperation("获取下拉列表")
    @RequestMapping(value = "/getDropDownForLineList/{line}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getDropDownForLineList(@PathVariable String line) {
        return AjaxResult.success(configLogisticsCompanyService.getDropDownForLineList(line));
    }

    @ApiOperation(value = "获取装箱单信息")
    @RequestMapping(value = "/getContainerInfo/{containerBatchNo}", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getContainerInfo(@PathVariable String containerBatchNo) {
        return containerService.getContainerInfo(containerBatchNo);
    }

    @ApiOperation(value = "查询待支付装箱批次")
    @RequestMapping(value = "/getWaitPayList", method = RequestMethod.GET)
    @ResponseBody
    public AjaxResult getWaitPayList(ContainerSearchConditionsDto containerSearchConditions) {
        //获取当前用户
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        containerSearchConditions.setCustomerId(currentUser.getUserId());
        containerSearchConditions.setContainerState(ConstantsUtil.CONTAINER_STATUS_1);
        return AjaxResult.success(containerService.getAllContainerList(containerSearchConditions));
    }

}
